package com.autoplaza;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class ContactoEmail extends Activity implements Runnable{
	EditText tnombre,temail,ttelefono,tcomentarios;
	ProgressDialog pd;
	Button btnestado,enviar;
	String[] estados={"Aguascalientes","Baja California","Baja California Sur","Campeche","Chiapas","Chihuahua",
			"Coahuila","Colima","Durango","Estado de México","Guanajuato","Guerrero","Hidalgo","Jalisco","Distrito Federal",
			"Michoacán","Morelos","Nayarit", "Nuevo León","Oaxaca","Puebla","Querétaro","Quintana Roo",
			"San Luis Potosí","Sinaloa","Sonora","Tabasco","Tamaulipas","Tlaxcala","Veracruz","Yucatán",
			"Zacatecas"};
	String marca, modelo, year, idanuncio,estadoid="1",nombreenvia,emailenvia,mensaje, result, telefono;
	
	
		
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.contactoemail);
		
		int size = Utils.getScreenSize2(ContactoEmail.this);
		if( size == 1){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 30));
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(30, 30));
		}		
		if( size == 2){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 60));	
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(45, 45));

		}		
		if( size == 3){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 80));
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(80, 80));

		}
		
		Bundle extras = getIntent().getExtras();
		if(extras != null){
			marca=extras.getString("marca");
			modelo=extras.getString("modelo");
			year=extras.getString("year");
			idanuncio=extras.getString("idanuncio");
			
		}
		
		
		btnestado=(Button) findViewById(R.id.btnestado);
		enviar=(Button) findViewById(R.id.enviaremail);
		tnombre=(EditText) findViewById(R.id.et_contacto_nombre);
		temail=(EditText) findViewById(R.id.et_contacto_email);
		ttelefono=(EditText) findViewById(R.id.txttelefono);
		tcomentarios=(EditText) findViewById(R.id.txtcomentario);
		btnestado.setText(estados[0]);
		btnestado.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				funcionIniciarContextMenuParaBoton2(btnestado);
			}
		});
		enviar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				progreso();
			}
		});
		
	}
	
	void progreso(){
		pd=ProgressDialog.show(this, "Espere por favor...", "Buscando...");
		Thread thread=new Thread(this);
		thread.start();
		
	}
	
	@Override
	public void run() {
		enviarMail();
		
	} 
	
protected void enviarMail() {
		
        InputStream is = null;
        
        
        try {
			nombreenvia=URLEncoder.encode(tnombre.getText().toString(), "utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		emailenvia=temail.getText().toString().trim();
		telefono=ttelefono.getText().toString().trim();
        
		try {
			mensaje=URLEncoder.encode(tcomentarios.getText().toString(), "utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	
		
		try{
		String url="http://www7.autos-usados.autoplaza.com.mx/systems/autos/xtSendToPropietarioBlack.asp"+
        "?anuncioid=" + idanuncio+
        "&NombreEnvia=" + nombreenvia+
        "&estadoid=" + estadoid+
        "&municipio="+
        "&municipioid="+
        "&telof1="+
        "&Telefono=" + telefono+
        "&EMailEnvia=" + emailenvia+
        "&mensaje=" + mensaje+
        "&marca=" + marca+
        "&modelo=" + modelo+
        "&anno=" + year;

		
		Log.i("URL", ""+url);

		URI myURI = null;
		try {
			myURI = new URI(url);
		} catch (URISyntaxException e) {
		}
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet getMethod = new HttpGet(myURI);
		HttpResponse webServerResponse = null;
		try {
			webServerResponse = httpClient.execute(getMethod);
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}
		
		HttpEntity httpEntity = webServerResponse.getEntity();
		
		if (httpEntity != null) {
			try {
				is = httpEntity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
	            StringBuilder sb = new StringBuilder();
	            String line = null;
	            while ((line = reader.readLine()) != null) {
	                    sb.append(line + "\n");
	            }
	            is.close();
	            result=sb.toString();
	            Log.i("response", ""+result);

			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
		}catch (Exception e) {
		}
		
		handler.sendEmptyMessage(0);
	}

	Handler handler=new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			Toast.makeText(getApplicationContext(), "Mensaje enviado correctamente", Toast.LENGTH_SHORT).show();
			pd.dismiss();
			pd.cancel();
			tnombre.setText("");
			temail.setText("");
			ttelefono.setText("");
			tcomentarios.setText("");
			
		};
		
	};
	
	
	public void funcionIniciarContextMenuParaBoton2(View v) {
		registerForContextMenu(v);
		openContextMenu(v);
	}
	
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Context Menu");  
		for(int i=0;i<estados.length;i++){
	        menu.add(0, v.getId(), 0, estados[i]);  
	        
		}
	}
	
	
	
	
	@Override  
    public boolean onContextItemSelected(MenuItem item) {  
		for(int i=0;i<estados.length;i++){
			if(item.getTitle().equals(estados[i])){
				btnestado.setText(estados[i]);
				int var=i+1;
				estadoid=""+var;
				
			}
		}

    return true;  
    }

	
  
}
